<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission({type:1,pid:0})">添加权限</el-button>
        </div>
        <!-- row-key="id":就是让表单数据以树状结构显示 -->
        <el-table border :data="permisstionList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <!-- code码加一个重复校验：不可以和已经存在的所有code码出现重复 -->
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="text" @click="addPermission({type:2,pid:row.id})">添加</el-button>
              <el-button type="text" @click="editPermission(row.id)">编辑</el-button>
              <el-button type="text" @click="delPermission(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 新增弹框 -->
      <el-dialog :visible="showDialog" title="弹层标题" @close="closeDialog">
        <el-form ref="addForm" label-width="100px" :model="formData" :rules="rules">
          <el-form-item label="权限名称" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="formData.code" />
          </el-form-item>
          <el-form-item label="权限描述" prop="description">
            <el-input v-model="formData.description" />
          </el-form-item>
          <el-form-item label="权限启用">
            <el-switch
              v-model="formData.enVisible"
              active-text="启用"
              active-value="1"
              inactive-text="不启用"
              inactive-value="0"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div style="text-align: right;">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="confirm">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {getPermissionList, delPermissionAPI, addPermissionAPI, getPermissionDetail, updatePermissionAPI} from '@/api/permission'
import tree from '@/utils/tree'
export default {
  name: 'PermissionVue',
  data(){
    // name验证
    const OneName = (rule, value, callback) => {
      if (this.formData.type === 1) {
        if (this.name1.includes(value)) {
          callback(new Error('一级不能和二级重复'))
        } else {
          callback()
        }
      } else {
        if (this.name2.includes(value)) {
          callback(new Error('二级不能和二级重复'))
        } else {
          callback()
        }
      }
    }
    // code验证
    // 要求：不能和同级出现重复，要在生成的codeList基础上再做一层过滤，以type作为过滤条件
    // 编辑状态下容许和自己重复-->根据当前form.id是否存在，对codeList做处理，如果编辑，就先把自己过滤掉，再校验
    const validateCode = (rule, value, callback) => {
      let codeList = []
      if (this.formData.type === 1){
        if (this.formData.id){
          // 这是编辑的一级code
          codeList = this.codeList.filter(item => item.type===1).map(item => item.code).filter(item => item!==this.currentCode)
        } else {
          // 这是新增的一级code
          codeList = this.codeList.filter(item => item.type===1).map(item => item.code)
        }
      } else if (this.formData.type === 2){
        if (this.formData.id){
          // 这是编辑的二级code
          codeList = this.codeList.filter(item => item.type===2).map(item => item.code).filter(item => item!==this.currentCode)
        } else {
          // 这是新增的二级code
          codeList = this.codeList.filter(item => item.type===2).map(item => item.code)
        }
      }
      if (codeList.includes(value)){
        callback(new Error('code不能重复'))
      } else {
        callback()
      }
      console.log(codeList)
    }
    return {
      permisstionList: [],
      // pid:如果点击的上面的添加，传固定的0，如果点击表格内的添加，则pid以当前行的id为主
      showDialog: false,
      // 传给服务端的数据
      formData: {
        name: '',
        code: '',
        description: '',
        enVisible: '',
        type: null,
        pid: ''
      },
      rules: {
        name: [{required: true, message: '权限名称必填', trigger: 'blur'},
          {validator: OneName, trigger: 'blur'}],
        code: [{required: true, message: '权限标识必填', trigger: 'blur'},
          {validator: validateCode, trigger: 'blur'}],
        description: [{required: true, message: '权限描述必填', trigger: 'blur'}]
      },
      // 用来验证权限名称
      name1: [],
      name2: [],
      codeList: [],
      currentCode: ''

      // codes: []
    }
  },
  mounted(){
    this.getPermissionList()
  },
  methods: {
    // 获取权限列表
    async getPermissionList(){
      const res = await getPermissionList()
      res.filter(item => item.type===1).forEach(item => this.name1.push(item.name));
      res.filter(item => item.type===2).forEach(item => this.name2.push(item.name));
      this.codeList = res
      // res.forEach(item => this.codes.push(item.code));
      this.permisstionList = tree(res)
    },
    // 删除权限节点
    delPermission(id){
      this.$confirm('确定删除权限节点吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await delPermissionAPI(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        // 重新渲染权限列表
        this.getPermissionList()
      }).catch(() => {
               
      });
    },
    // 点击添加，显示弹框
    addPermission({type, pid}){
      this.showDialog = true
      this.formData.type = type
      this.formData.pid = pid
    },
    // 关闭弹框
    closeDialog(){
      this.showDialog = false
      this.resetForm()

    },
    // 清除表单数据 + 校验
    resetForm(){
      this.$refs.addForm.resetFields()
      this.formData={
        name: '',
        code: '',
        description: '',
        enVisible: '',
        type: null,
        pid: ''
      }
    },
    // 添加权限节点
    async confirm(){
      if (this.formData.id){
        // 编辑更新权限
        await updatePermissionAPI(this.formData)
        this.$message.success( `编辑权限成功`)
      } else {
        // 添加权限节点
        await addPermissionAPI(this.formData)
        this.$message.success( `新增权限成功`)
      }
      
      this.getPermissionList()
      this.closeDialog()
      this.resetForm()
      
    },
    // 取消按钮
    cancel(){
      this.closeDialog = false
      this.resetForm()
    },
    // 编辑权限节点
    async  editPermission(id){
      this.showDialog = true
      // 获取当前权限的详情
      this.formData = await getPermissionDetail(id)
      this.currentCode = this.formData.code
    }
  }
}
</script>

<style>
</style>
